package iscas.order.controller;

import iscas.order.clients.PayFeignClient;
import iscas.order.clients.ReserveFeignClient;
import iscas.order.common.CustomResult;
import iscas.order.dto.OrderDTO;
import iscas.order.dto.PayDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private PayFeignClient payFeignClient;

    @Autowired
    private ReserveFeignClient  reserveFeignClient;

    @PostMapping("/addOrder")
    public CustomResult addOrder(@RequestBody OrderDTO orderDTO) {
        String orderContent = orderDTO.getOrderContent();
        String userId = orderDTO.getOrderUserId();
        String price = orderDTO.getOrderPrice();
        // 首先请求库存服务来确认库存
        // String reserveUrl = "http://localhost:8004/api/reserve/getReserve?orderContent=" + orderContent;
        CustomResult reserveResult = reserveFeignClient.getReserve(orderContent);
        System.out.println("我是新版！");
        // 检查库存服务的响应
        if (reserveResult != null && reserveResult.getStatus() == 20000) {
            // 库存确认后请求支付服务 Post请求
            CustomResult payResult = payFeignClient.topay(new PayDTO(userId, price));
            //  检查支付服务的响应
            if (payResult != null && payResult.getStatus() == 20000) {
                return new CustomResult(20000, "下单成功", null);
            } else {
                return new CustomResult(40000, "支付失败", null);
            }
        } else {
            return new CustomResult(40000, "库存不足", null);
        }
    }
}
